package com.lsa.blog.service.Impl;

import com.lsa.blog.Dao.TypeRepository;
import com.lsa.blog.NotFoundException;
import com.lsa.blog.po.Type;
import com.lsa.blog.service.TypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class TypeServiceImpl implements TypeService {

    @Autowired
    private TypeRepository repository;

    /**
     * 保存分类名称
     * @param type 分类名称
     * @return
     */
    @Transactional
    @Override
    public Type saveType(Type type) {
        return repository.save(type);
    }

    /**
     * 根据id查找分类
     * @param id
     * @return
     */
    @Transactional
    @Override
    public Type getType(Long id) {
        return repository.findById(id).orElse(null);
    }

    /**
     * 根据分类名称查找
     * @param name
     * @return
     */
    @Override
    public Type getTypeByName(String name) {
        return repository.findByName(name);
    }

    /**
     * 分页，查询类型
     * @param pageable
     * @return
     */
    @Transactional
    @Override
    public Page<Type> listType(Pageable pageable) {
        return repository.findAll(pageable);
    }

    /**
     * 分页，查询类型
     * @return
     */
    @Override
    public List<Type> listType() {
        return repository.findAll();
    }

    /**
     * 分页，根据传入的参数决定查询几个（前几个）类型
     * @param size
     * @return
     */
    @Override
    public List<Type> listTypeTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC,"blogs.size");
        Pageable pageable = PageRequest.of(0,size,sort);
        return repository.findTop(pageable);
    }

    /**
     * 修改分类
     * @param id
     * @param type
     * @return
     */
    @Transactional
    @Override
    public Type updateType(Long id, Type type) {
        Type t = repository.findById(id).orElse(null);
        if (t == null){
            throw new NotFoundException("不存在该类型");
        }
        BeanUtils.copyProperties(type,t);
        return repository.save(t);
    }

    /**
     * 根据id删除分类
     * @param id
     */
    @Transactional
    @Override
    public void deleteTyle(Long id) {
        repository.deleteById(id);

    }
}
